﻿using Newtonsoft.Json;
using BuyingSpree_HPV.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace BuyingSpree_HPV.Help
{
    public class Network
    {
        protected internal static ServiceResponse HttpGet(string url, Dictionary<string, object> parameter = null, Dictionary<string, string> Headers = null)
        {
            try
            {
                string result = ""; //返回结果
                Encoding encoding = Encoding.UTF8;
                string parStr = "";
                if (parameter != null)
                {
                    foreach (var item in parameter)
                    {
                        parStr += item.Key + "=" + item.Value + "&";
                    }
                    url += "?" + parStr.TrimEnd(Convert.ToChar("&"));
                }
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "GET";
                wbRequest.Accept = "*/*";
                wbRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Linux; Android 5.1.1; SM-N960F Build/JLS36C; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 MMWEBID/1042 MicroMessenger/7.0.15.1680(0x27000F34) Process/appbrand0 WeChat/arm32 NetType/WIFI Language/zh_CN ABI/arm32");
                wbRequest.Headers.Add("Referer", "https://servicewechat.com/wxff8cad2e9bf18719/2/page-frame.html");
                wbRequest.Headers.Add("tk", Config.HeaderConfig.tk);
                wbRequest.Headers.Add("Accept", "application/json, text/plain, */*");
                wbRequest.Headers.Add("Host", "miaomiao.scmttec.com");
                wbRequest.Headers.Add("Cookie", Config.HeaderConfig.cookies);
                if (Headers!=null)
                {
                    wbRequest.Headers.Add(Headers.First().Key, Headers.First().Value);
                }
                HttpWebResponse responseWeb = (HttpWebResponse)wbRequest.GetResponse();
                Stream responseStream = responseWeb.GetResponseStream();
                using (StreamReader sReader = new StreamReader(responseStream))
                {
                    result = sReader.ReadToEnd();
                }
                responseStream.Dispose();
                ServiceResponse response = JsonConvert.DeserializeObject<ServiceResponse>(result);
                if (!response.code.Equals("0000"))
                {
                    Exception ex = new Exception($"接口请求失败,请联系开发人员处理-url--{url}");
                    throw ex;
                }
                return response;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
